package com.example.controller;

import com.example.entity.LoginRequest;
import com.example.utils.JwtSuperUtil;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
/**
 * 跨域问题第一种解决方式
 */
//@CrossOrigin(origins = "*")
public class AuthController {

    @PostMapping("login")
    public ResponseEntity<String> login(@RequestBody LoginRequest request) {
        /**
         * 模拟账号校验（实际应查数据库）
         */
        if ("admin".equals(request.getUsername()) && "123456".equals(request.getPassword())) {
            String token = JwtSuperUtil.generateToken(request.getUsername());
            /**
             * 返回给前端保存
             */
            return ResponseEntity.ok(token);
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
        }
    }

    @GetMapping("/me")
    public ResponseEntity<String> me(@RequestHeader("Authorization") String authHeader) {
        String token = authHeader.replace("Bearer ", "");
        Claims claims = JwtSuperUtil.parseToken(token);
        return ResponseEntity.ok(claims.getSubject());
    }

    @GetMapping("/test")
    public ResponseEntity<String> test() {
        return ResponseEntity.ok("CORS 配置生效");
    }

}
